package com.hot12345.server.DBConnection;

import java.io.Reader;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
import com.hot12345.common.util.ReadProperties;

public class IbatisConnectCommImpl {

	private static final Log log = LogFactory.getLog(IbatisConnectCommImpl.class);	
	private static Map<String,SqlMapClient> clientMap = new HashMap<String,SqlMapClient>();
	
	public static Map<String, SqlMapClient> getClientMap() {
		return clientMap;
	}

	public static void setClientMap(Map<String, SqlMapClient> clientMap) {
		IbatisConnectCommImpl.clientMap = clientMap;
	}
	
	private IbatisConnectCommImpl(){
		
	}
	
	public static SqlMapClient getSqlMapClient(String ds) throws Exception {
		return createMySqlClient(ds);
	}
	
	private static SqlMapClient createMySqlClient(String ds) throws Exception {
		String sqlMapClientKey = null;
		log.debug("ds=" + ds);
		if(ds==null || "".equals(ds.trim())){
			throw new Exception("ds is null");
		} else {
			sqlMapClientKey = ds;
		}
		
		//if(clientMap.get(sqlMapClientKey)==null || !(clientMap.get(sqlMapClientKey) instanceof SqlMapClient)) {
		if(clientMap.get(sqlMapClientKey)==null) {  
			log.debug("sqlMapClientKey="+sqlMapClientKey);
			//同步
			synchronized (sqlMapClientKey){
				 if(clientMap.get(sqlMapClientKey)==null){
			String sqlMapConfig = ReadProperties.readValue(sqlMapClientKey);
			if(sqlMapConfig==null){
				log.error("not found sqlMapConfig file,sqlMapClientKey:" + sqlMapClientKey);
				throw new Exception("not found sqlMapConfig file,sqlMapClientKey:" + sqlMapClientKey);
			}   			
			 try {
		            //读取SqlMapConfig的资源配置
		            Reader reader = Resources.getResourceAsReader(sqlMapConfig);
		            //构件一个SqlMapClient的实例
		            SqlMapClient sqlMapClient = SqlMapClientBuilder.buildSqlMapClient(reader);
		            
		            //通过获取一个连接的方式进行初始化连接池,如果不进行这一步，连接池将会在连接首次被使用的时候才创建。
		            sqlMapClient.getDataSource().getConnection();
		            clientMap.put(sqlMapClientKey,sqlMapClient);
		            //关闭输入流
		            reader.close();
		        } catch (Exception e) {
		        	log.error("Exception",e);
		            throw new RuntimeException("在构件SqlMapClient_mysql实例的时候发生了异常！", e);
		        } 
				}
			}  
		}
		log.debug("============================================================");
		log.debug("load "+ sqlMapClientKey +" success!");
		log.debug("============================================================");
		return clientMap.get(sqlMapClientKey);
	}
}
